<?php

namespace app\models;

use Yii;
use yii\base\Exception;
use yii\data\Pagination;
use yii\db\ActiveRecord;
use ZipArchive;
/**
 * 卡
 * Class Card
 * @package app\models
 * @agentpackage app\models
 *
 * @property integer $id PK
 * @property integer $api_id 接口编号
 * @property integer $isp_id 运营商编号
 * @property integer $agent_id 代理商编号
 * @property integer $uid 用户编号
 * @property integer $package_id 套餐编号
 * @property string $iccid 集成电路卡识别码20位字符
 * @property string $msisdn 物联卡号码最长13位数字
 * @property string $imsi 国际移动用户识别码不超过15位
 * @property integer $sms_ignore_sign 发送短信时是否忽略签名
 * @property integer $status 状态
 * @property string $batch_no 批次号
 * @property integer $create_time 创建时间
 * @property integer $dispatch_time 分配给用户时间
 * @property integer $active_time 激活时间
 * @property integer $on_off 开关机
 * @property string $ip IP地址
 * @property float $data 数据用量（B）
 * @property integer $sms 短信用量（条）
 * @property integer $voice 语音用量（分钟）
 * @property integer $refresh_time 刷新时间
 * @property integer $term_length 套餐有效期
 * @property integer $term_length_unit 套餐有效期单位
 * @property integer $term_end_time 套餐结束时间
 * @property integer $attr_update_time 属性更新时间
 * @property string $remark 备注
 *
 * @property Api $api 关联接口
 * @property Isp $isp 关联运营商
 * @property Agent $agent 关联代理商
 * @property User $user 关联用户
 * @property Package $package 关联套餐
 * @property AgentPackage $agentpackage 关联代理商套餐
 */
class Card extends ActiveRecord
{
    const STATUS_TEST_READY = 1; // 可测试
    const STATUS_INVENTORY = 2; // 库存
    const STATUS_ACTIVATION_READY = 3; // 可激活
    const STATUS_ACTIVATED = 4; // 已激活
    const STATUS_DEACTIVATED = 5; // 已停用
    const STATUS_RETIRED = 6; // 已失效

    const TERM_LENGTH_UNIT_MINUTE = 1; // 套餐有效期单位分钟
    const TERM_LENGTH_UNIT_DAY = 2; // 套餐有效期单位天
    const TERM_LENGTH_UNIT_MONTH = 3; // 套餐有效期单位月

    // 状态转换限制
    const STATUS_TRANSFORM_MAP = [
        Card::STATUS_TEST_READY => [
            Card::STATUS_INVENTORY,
            Card::STATUS_ACTIVATION_READY,
            Card::STATUS_RETIRED,
        ],
        Card::STATUS_INVENTORY => [
            Card::STATUS_ACTIVATION_READY,
            Card::STATUS_RETIRED,
        ],
        Card::STATUS_ACTIVATION_READY => [
            Card::STATUS_INVENTORY,
            Card::STATUS_RETIRED,
        ],
        Card::STATUS_ACTIVATED => [
            Card::STATUS_DEACTIVATED,
            Card::STATUS_RETIRED,
        ],
        Card::STATUS_DEACTIVATED => [
            Card::STATUS_ACTIVATED,
            Card::STATUS_RETIRED,
        ],
        Card::STATUS_RETIRED => [
            Card::STATUS_DEACTIVATED,
        ],
    ];
    public $pname;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['api_id', 'isp_id'], 'required'],
            ['api_id', 'exist', 'targetClass' => Api::class, 'targetAttribute' => 'id'],
            ['isp_id', 'exist', 'targetClass' => Isp::class, 'targetAttribute' => 'id'],
            ['uid', 'exist', 'targetClass' => User::class, 'targetAttribute' => 'id'],
            ['package_id', 'exist', 'targetClass' => Package::class, 'targetAttribute' => 'id'],
            ['iccid', 'string', 'max' => 32],
            [['msisdn', 'imsi','Imei'], 'string', 'max' => 16],
            ['remark', 'safe'],
            ['batch_no', 'string', 'max' => 32],
            ['xuzhi','safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'api_id' => '接口',
            'isp_id' => '运营商',
            'package_id' => '套餐',
            'iccid' => 'ICCID',
            'msisdn' => 'MSISDN',
            'imsi' => 'IMSI',
            'Imei' => 'IMEI',
            'remark' => '备注',
            'batch_no' => '批次号',
            'xuzhi' => '虚值系数'
        ];
    }

    /**
     * 生成新的批次号
     * @param integer $mid 管理用户编号，0表示系统自动添加
     * @return string
     */
    public static function generateBatchNo($mid = 0)
    {
        return date('YmdHis') . Util::randomStr(6) . $mid;
    }

    /**
     * 关联接口
     * @return \yii\db\ActiveQuery
     */
    public function getApi()
    {
        return $this->hasOne(Api::class, ['id' => 'api_id']);
    }

    /**
     * 关联运营商
     * @return \yii\db\ActiveQuery
     */
    public function getIsp()
    {
        return $this->hasOne(Isp::class, ['id' => 'isp_id']);
    }

    /**
     * 关联代理商
     * @return \yii\db\ActiveQuery
     */
    public function getAgent()
    {
        return $this->hasOne(Agent::class, ['id' => 'agent_id']);
    }

    /**
     * 关联用户
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'uid']);
    }

    /**
     * 关联套餐
     * @return \yii\db\ActiveQuery
     */
    public function getPackage()
    {
        return $this->hasOne(Package::class, ['id' => 'package_id']);
    }
	/**
     * 关联代理商套餐
     * @return \yii\db\ActiveQuery
     */
    public function getAgentPackage()
    {
        return $this->hasOne(AgentPackage::class, ['package_id' => 'package_id'])->where(['agent_id' => $this->agent_id]);
    }
    
	
    //年包充值加油包解除限速操作
    public function stopNetworkAccess(){
        $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'StopEditNetworkAccessConfigCs',
            'iccid'  => $this->iccid,
            'setStatus' => "1208535"
            );
        $string = json_encode($data);
        $config = System::findOne(['name'=>'api_url']);
        $url = $config->value;
        $cuiotPost =  $this->postUrl($url,$string);
        $arr = json_decode($cuiotPost,true);
        if($arr['retcode'] == 200){
            return [
            'code' => 1,
            'msg' => '解除限制成功',
            'data' => '',
            ];
            exit;
        }else{
            return [
            'code' => 1001,
            'msg' => '解除限制异常',
            'data' => '',
            ];
            exit;
        }
    }
    //充值完成激活卡操作
    public function setActive(){
        $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'setCardStatus',
            'iccid'  => $this->iccid,
            'setStatus' => "4",
            'source' => "chongzhijihuo"

            );
            $string = json_encode($data);
            $config = System::findOne(['name'=>'api_url']);
            $url = $config->value;
            $cuiotPost =  $this->postUrl($url,$string);
            $arr = json_decode($cuiotPost,true);
            if($arr['retcode'] == 200){
                return [
                'code' => 1,
                'msg' => '激活成功',
                'data' => '',
                ];
                exit;
            }else{
                return [
                'code' => 1001,
                'msg' => '激活异常',
                'data' => '',
                ];
                exit;
            }
    }
    //管理后台更改卡状态
    public function setExecute($card,$status){
        $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'setCardStatus',
            'iccid'  => $card,
            'setStatus' => $status,
            'source' => "guanlicaozuo"
            );
        $string = json_encode($data);
        $config = System::findOne(['name'=>'api_url']);
        $url = $config->value;
        $cuiotPost =  $this->postUrl($url,$string);
        $arr = json_decode($cuiotPost,true);
        if($arr['retcode'] == 200){
            return [
            'code' => 1,
            'msg' => '激活成功',
            'data' => '',
            ];
            exit;
        }else{
            return [
            'code' => 1001,
            'msg' => '激活异常',
            'data' => '',
            ];
            exit;
        }
    }
    //新刷新卡状态和用量
    public function newRefreshBasic(){
        if(empty($this->api_id)){
            return false;
        }
            $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'CardCycle',
            'iccid'  => $this->iccid
            );
            $string = json_encode($data);
            $config = System::findOne(['name'=>'api_url']);
            $url = $config->value;
            $cuiotPost =  $this->postUrl($url,$string);
            $arr = json_decode($cuiotPost,true);
            if($arr['retcode'] == 200){
                $status = $arr['status'];
                $data = $arr['data'];
            }elseif($arr['retcode'] == 509){
                $status = $this->status;
                $data = $this->data;
            }else{
                $status = $this->status;
                $data = $this->data;
            }
            $this->updateAttributes(['refresh_time' => time(), 'data' => $data, 'status' => $status,'term_length' => $this->term_length]);
            $this->updateTermEnd(); 
    }
    //刷新卡状态，不计算结束时间
    public function newRefreshCard(){
        if(empty($this->api_id)){
            return false;
        }
            $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'CardCycle',
            'iccid'  => $this->iccid
            );
            $string = json_encode($data);
            $config = System::findOne(['name'=>'api_url']);
            $url = $config->value;
            $cuiotPost =  $this->postUrl($url,$string);
            $arr = json_decode($cuiotPost,true);
            if($arr['retcode'] == 200){
                $status = $arr['status'];
                $data = $arr['data'];
            }elseif($arr['retcode'] == 509){
                $status = $this->status;
                $data = $this->data;
            }else{
                $status = $this->status;
                $data = $this->data;
            }
            $this->updateAttributes(['refresh_time' => time(), 'data' => $data, 'status' => $status]);
    }
    //执行新刷新卡状态和用量后执行更新结束时间
    public function updateTermEnd(){
        if (empty($this->term_length_unit)) {
            return 0;
        }
        $endTime = $this->active_time;
        $term_length = $this->term_length;
        $total_flow = $this->total_flow;
        $endate = $endTime + (30*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
        return $this->updateAttributes(['term_end_time' => $endtime,'term_length'=>$term_length,'total_flow'=>$total_flow]);
    }
    /**
     * 刷新卡基本信息
     * @return bool
     * @throws \Exception
     */
    public function refreshBasic()
    {
        if (empty($this->api_id)) {
            return false;
        }
        if ($this->api_id == 1) { // Jasper接口
            $api = new \app\models\jasper\Api($this->isp->data);
            // 刷新基本信息
            $resp = $api->GetTerminalDetails([$this->iccid]);
            $terminal = $resp->terminals->terminal; // 单条查询返回的是对象
            $cardBasic = CardBasic::findOne(['card_id' => $this->id]);
            if (empty($cardBasic)) {
                $cardBasic = new CardBasic();
                $cardBasic->card_id = $this->id;
            }
            $cardBasic->refresh_time = time();
            $cardBasic->loadFromRefreshData($terminal);
            // 刷新在线状态
            $this->updateAttributes(['refresh_time' => time(), 'on_off' => 0, 'ip' => null]); // 先设置为关机
            $resp = $api->GetSessionInfo([$this->iccid]);
            $sessionInfo = $resp->sessionInfo;
            if (isset($sessionInfo->session)) {
                if (is_array($sessionInfo->session)) {
                    $sessionList = $sessionInfo->session;
                } else {
                    $sessionList = [$sessionInfo->session];
                }
                foreach ($sessionList as $session) {
                    if ($session->iccid == $this->iccid) {
                        $this->updateAttributes(['on_off' => 1, 'ip' => $session->ipAddress]);
                    }
                }
            }
        } elseif ($this->api_id == 2) { // 山东移动接口
            $api = new \app\models\sdiot\Api($this->isp->data);
            // 刷新基本信息
            if (empty($this->iccid) || empty($this->msisdn) || empty($this->imsi)) {
                if (!empty($this->iccid)) {
                    $json = $api->cmiotQryNumberInfo(2, $this->iccid);
                } elseif (!empty($this->msisdn)) {
                    $json = $api->cmiotQryNumberInfo(1, $this->msisdn);
                } elseif (!empty($this->imsi)) {
                    $json = $api->cmiotQryNumberInfo(3, $this->imsi);
                } else {
                    throw new Exception('卡信息错误。');
                }
                $this->iccid = $json['ICCID'];
                $this->msisdn = $json['MSISDN'];
                $this->imsi = $json['IMSI'];
                $this->save(false);
            }
            // 状态信息
            $status = $api->cmiotQryUserStatusRealSingle($this->msisdn);
            if ($status == '00') {
                if (in_array($this->status, [Card::STATUS_DEACTIVATED, Card::STATUS_RETIRED])) {
                    $this->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                }
                // 激活时间及套餐有效期
                if (empty($this->active_time)) {
                    $json = $api->bossQrySubsPackage($this->msisdn);
                    if (!empty($json)) {
                        $isTest = false;
                        foreach ($json as $package) {
                            if (preg_match('/测试期/', $package['bunessname'])) {
                                $isTest = true;
                            }
                        }
                        if ($isTest) {
                            $this->updateAttributes(['status' => Card::STATUS_TEST_READY]);
                        } else {
                            $this->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                            foreach ($json as $package) {
                                if ($package['bunesscode'] == 'M2M.I00010100085') {
                                    $this->updateAttributes(['active_time' => strtotime($package['starttime'])]);
                                    $this->calcTermEnd();
                                }
                            }
                        }
                    }
                }
            } else {
                $statusMap = [
                    '07' => Card::STATUS_ACTIVATION_READY, // 待激
                    '01' => Card::STATUS_DEACTIVATED, // 单向停机
                    '02' => Card::STATUS_DEACTIVATED, // 停机
                    '03' => Card::STATUS_DEACTIVATED, // 预销号
                    '04' => Card::STATUS_DEACTIVATED, // 销号
                    '05' => Card::STATUS_DEACTIVATED, // 过户
                    '06' => Card::STATUS_DEACTIVATED, // 休眠
                    '99' => Card::STATUS_RETIRED, // 号码不存在
                ];
                if (isset($statusMap[$status])) {
                    $this->updateAttributes(['status' => $statusMap[$status]]);
                }
            }
            // 流量情况
            $json = $api->cmiotQryCurMonthGprsUsedInfo(1, $this->msisdn);
            $data = $json['total_gprs'] * 1024;
            $sms = $api->cmiotQrySMSUsedInfo(1, $this->msisdn);
            $this->updateAttributes(['data' => $data, 'sms' => $sms, 'voice' => 0]);
            // 刷新在线状态
            $json = $api->cmiotQryGPRSInfo($this->msisdn);
            $ip = isset($json['IP']) ? $json['IP'] : null;
            $onOff = $api->cmiotQryOnAndOffRealSingle($this->msisdn);
            $this->updateAttributes(['refresh_time' => time(), 'on_off' => $onOff, 'ip' => $ip]);
        } elseif ($this->api_id == 3) { // 中移接口
            $api = new \app\models\cmiot\Api($this->isp->data);
            // 刷新基本信息
            if (empty($this->iccid) || empty($this->msisdn) || empty($this->imsi)) {
                if (!empty($this->iccid)) {
                    $json = $api->cardinfo($this->iccid, 2);
                } elseif (!empty($this->msisdn)) {
                    $json = $api->cardinfo($this->msisdn, 0);
                } elseif (!empty($this->imsi)) {
                    $json = $api->cardinfo($this->imsi, 1);
                } else {
                    throw new Exception('卡信息错误。');
                }
                $this->iccid = $json['ICCID'];
                $this->msisdn = $json['MSISDN'];
                $this->imsi = $json['IMSI'];
                $this->save(false);
            }
            // 状态信息
            $status = $api->userstatusrealsingle($this->msisdn);
            if ($status == '00') {
                //$json = $api->querycardlifecycle($this->msisdn);
                //if ($json['lifecycle'] == '01') {
                //    $this->updateAttributes(['status' => Card::STATUS_TEST_READY]);
                //} else {
                //    $this->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                //    if (empty($this->active_time)) {
                //        $this->updateAttributes(['active_time' => strtotime($json['opentime'])]);
                //    }
                //}
                //if (in_array($this->status, [Card::STATUS_DEACTIVATED, Card::STATUS_RETIRED])) {
                    $this->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                //}
                // 激活时间及套餐有效期
                if (empty($this->active_time)) {
                    $json = $api->querycardprodinfo($this->msisdn);
                    if (!empty($json['prodinfos'])) {
                        $isTest = false;
                        foreach ($json['prodinfos'] as $prod) {
                            if (preg_match('/测试期/', $prod['prodname'])) {
                                $isTest = true;
                            }
                        }
                        if ($isTest) {
                            $this->updateAttributes(['status' => Card::STATUS_TEST_READY]);
                        } else {
                            $this->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                            foreach ($json['prodinfos'] as  $prod) {
                                if ($prod['prodid'] == 'I00010100085') {
                                    $this->updateAttributes(['active_time' => strtotime($prod['prodinstefftime'])]);
                                    $this->calcTermEnd();
                                }
                            }
                        }
                    }
                }
            } else {
                $statusMap = [
                    '07' => Card::STATUS_ACTIVATION_READY, // 待激
                    '00' => Card::STATUS_ACTIVATED, // 已激活
                    '01' => Card::STATUS_DEACTIVATED, // 单向停机
                    '02' => Card::STATUS_DEACTIVATED, // 停机
                    '03' => Card::STATUS_DEACTIVATED, // 预销号
                    '04' => Card::STATUS_DEACTIVATED, // 销号
                    '05' => Card::STATUS_DEACTIVATED, // 过户
                    '06' => Card::STATUS_DEACTIVATED, // 休眠
                    '99' => Card::STATUS_RETIRED, // 号码不存在
                ];
                if (isset($statusMap[$status])) {
                    $this->updateAttributes(['status' => $statusMap[$status]]);
                }
            }
            // 流量情况
            $data = $api->gprsusedinfosingle($this->msisdn) * 1024;
            $sms = $api->smsusedinfosingle($this->msisdn);
            $this->updateAttributes(['data' => $data, 'sms' => $sms, 'voice' => 0]);
            // 刷新在线状态
            $json = $api->gprsrealsingle($this->msisdn);
            $ip = $json['IP'];
            $onOff = $api->onandoffrealsingle($this->msisdn);
            $this->updateAttributes(['refresh_time' => time(), 'on_off' => $onOff, 'ip' => $ip]);
        }
        if (!empty($this->uid) && !empty($this->package_id)) {
            UserPackagePool::calcPool($this->uid, $this->package_id);
        }
        return true;
    }

    /**
     * 更新套餐结束时间
     * @return int >0表示更新成功
     */
    public function calcTermEnd()
    {
        if (empty($this->term_length_unit)) {
            return 0;
        }
        $endTime = $this->active_time;
        $term_length = $this->term_length;
        $total_flow = $this->total_flow;
        switch ($this->term_length_unit) {
            case Card::TERM_LENGTH_UNIT_MINUTE: // 分钟
                $endTime += $this->term_length * 60;
                break;
            case Card::TERM_LENGTH_UNIT_DAY: // 天
                $endTime += $this->term_length * 86400;
                break;
            case Card::TERM_LENGTH_UNIT_MONTH: // 月
                //$endTime = strtotime(date('Ym01', $endTime) . ' +' . $this->term_length . 'month') - 1;
                $endTime = $this->active_time + (30*86400)*$this->term_length;
                break;
            default:
        }
        return $this->updateAttributes(['term_end_time' => $endTime,'term_length'=>$term_length,'total_flow'=>$total_flow]);
    }

    /**
     * 批量刷新卡信息
     * @param integer $ispId 接口编号
     * @param array $iccidList ICCID列表
     * @throws \Exception
     */
    public static function batchRefreshBasic($ispId, $iccidList)
    {
        $isp = Isp::findOne(['id' => $ispId]);
        if ($isp->api_id == 1) { // Jasper接口
            $api = new \app\models\jasper\Api($isp->data);
            // 刷新基本信息
            $resp = $api->GetTerminalDetails($iccidList);
            if (count($iccidList) == 1) {
                $terminalList = [$resp->terminals->terminal];
            } else {
                $terminalList = $resp->terminals->terminal;
            }
            foreach ($terminalList as $terminal) {
                $card = Card::findOne(['iccid' => $terminal->iccid]);
                $card->refresh_time = time();
                $card->on_off = 0;
                $card->ip = null;
                $card->save(false);
                $cardBasic = CardBasic::findOne(['card_id' => $card->id]);
                if (empty($cardBasic)) {
                    $cardBasic = new CardBasic();
                    $cardBasic->card_id = $card->id;
                }
                $cardBasic->refresh_time = time();
                $cardBasic->loadFromRefreshData($terminal);
            }
            // 刷新在线状态
            $resp = $api->GetSessionInfo($iccidList);
            $sessionInfo = $resp->sessionInfo;
            if (isset($sessionInfo->session)) {
                if (is_array($sessionInfo->session)) {
                    $sessionList = $sessionInfo->session;
                } else {
                    $sessionList = [$sessionInfo->session];
                }
                foreach ($sessionList as $session) {
                    $card = Card::findOne(['iccid' => $session->iccid]);
                    $card->updateAttributes(['on_off' => 1, 'ip' => $session->ipAddress]);
                }
            }
        } elseif ($isp->api_id == 2) { // 山东移动接口
            $api = new \app\models\sdiot\Api($isp->data);
            foreach ($iccidList as $iccid) {
                $card = Card::findOne(['iccid' => $iccid]);
                // 刷新基本信息
                $json = $api->cmiotQryNumberInfo(2, $card->iccid);
                $card->iccid = $json['ICCID'];
                $card->msisdn = $json['MSISDN'];
                $card->imsi = $json['IMSI'];
                $card->save(false);
                // 状态信息
                $status = $api->cmiotQryUserStatusRealSingle($card->msisdn);
                if ($status == '00') {
                    if (in_array($card->status, [Card::STATUS_DEACTIVATED, Card::STATUS_RETIRED])) {
                        $card->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                    }
                    // 激活时间及套餐有效期
                    if (empty($card->active_time)) {
                        $json = $api->bossQrySubsPackage($card->msisdn);
                        if (!empty($json)) {
                            $isTest = false;
                            foreach ($json as $package) {
                                if (preg_match('/测试期/', $package['bunessname'])) {
                                    $isTest = true;
                                }
                            }
                            if ($isTest) {
                                $card->updateAttributes(['status' => Card::STATUS_TEST_READY]);
                            } else {
                                $card->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                                foreach ($json as $package) {
                                    if ($package['bunesscode'] == 'M2M.I00010100085') {
                                        $card->updateAttributes(['active_time' => strtotime($package['starttime'])]);
                                        $card->calcTermEnd();
                                    }
                                }
                            }
                        }
                    }
                } else {
                    $statusMap = [
                        '07' => Card::STATUS_ACTIVATION_READY, // 待激
                        '01' => Card::STATUS_DEACTIVATED, // 单向停机
                        '02' => Card::STATUS_DEACTIVATED, // 停机
                        '03' => Card::STATUS_DEACTIVATED, // 预销号
                        '04' => Card::STATUS_DEACTIVATED, // 销号
                        '05' => Card::STATUS_DEACTIVATED, // 过户
                        '06' => Card::STATUS_DEACTIVATED, // 休眠
                        '99' => Card::STATUS_RETIRED, // 号码不存在
                    ];
                    if (isset($statusMap[$status])) {
                        $card->updateAttributes(['status' => $statusMap[$status]]);
                    }
                }
                // 流量情况
                $json = $api->cmiotQryCurMonthGprsUsedInfo(1, $card->msisdn);
                $data = $json['total_gprs'] * 1024;
                $sms = $api->cmiotQrySMSUsedInfo(1, $card->msisdn);
                $card->updateAttributes(['data' => $data, 'sms' => $sms, 'voice' => 0]);
                // 刷新在线状态
                $onOff = $api->cmiotQryOnAndOffRealSingle($card->msisdn);
                $json = $api->cmiotQryGPRSInfo($card->msisdn);
                $ip = isset($json['IP']) ? $json['IP'] : null;
                $card->updateAttributes(['refresh_time' => time(), 'on_off' => $onOff, 'ip' => $ip]);
            }
        } elseif ($isp->api_id == 3) { // 中移接口
            $api = new \app\models\cmiot\Api($isp->data);
            foreach ($iccidList as $iccid) {
                $card = Card::findOne(['iccid' => $iccid]);
                // 刷新基本信息
                if (empty($card->msisdn) || empty($card->imsi)) {
                    $json = $api->cardinfo($card->iccid, 2);
                    $card->iccid = $json['ICCID'];
                    $card->msisdn = $json['MSISDN'];
                    $card->imsi = $json['IMSI'];
                    $card->save(false);
                }
                // 状态信息
                $status = $api->userstatusrealsingle($card->msisdn);
                if ($status == '00') {
                   // $json = $api->querycardlifecycle($card->msisdn);
                   // if ($json['lifecycle'] == '01') {
                   //     $card->updateAttributes(['status' => Card::STATUS_TEST_READY]);
                   // } else {
                   //     $card->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                   //     if (empty($card->active_time)) {
                   //         $card->updateAttributes(['active_time' => strtotime($json['opentime'])]);
                   //     }
                   // }
                    //if (in_array($card->status, [Card::STATUS_DEACTIVATED, Card::STATUS_RETIRED])) {
                        $card->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                    //}
                    // 激活时间及套餐有效期
                    if (empty($card->active_time)) {
                        $json = $api->querycardprodinfo($card->msisdn);
                        if (!empty($json['prodinfos'])) {
                            $isTest = false;
                            foreach ($json['prodinfos'] as $prod) {
                                if (preg_match('/测试期/', $prod['prodname'])) {
                                    $isTest = true;
                                }
                            }
                            if ($isTest) {
                                $card->updateAttributes(['status' => Card::STATUS_TEST_READY]);
                            } else {
                                $card->updateAttributes(['status' => Card::STATUS_ACTIVATED]);
                                foreach ($json['prodinfos'] as  $prod) {
                                    if ($prod['prodid'] == 'I00010100085') {
                                        $card->updateAttributes(['active_time' => strtotime($prod['prodinstefftime'])]);
                                        $card->calcTermEnd();
                                    }
                                }
                            }
                        }
                    }
                } else {
                    $statusMap = [
                        '07' => Card::STATUS_ACTIVATION_READY, // 待激
                        '01' => Card::STATUS_DEACTIVATED, // 单向停机
                        '02' => Card::STATUS_DEACTIVATED, // 停机
                        '03' => Card::STATUS_DEACTIVATED, // 预销号
                        '04' => Card::STATUS_DEACTIVATED, // 销号
                        '05' => Card::STATUS_DEACTIVATED, // 过户
                        '06' => Card::STATUS_DEACTIVATED, // 休眠
                        '99' => Card::STATUS_RETIRED, // 号码不存在
                    ];
                    if (isset($statusMap[$status])) {
                        $card->updateAttributes(['status' => $statusMap[$status]]);
                    }
                }
                // 流量情况
                $data = $api->gprsusedinfosingle($card->msisdn) * 1024;
                $sms = $api->smsusedinfosingle($card->msisdn);
                $card->updateAttributes(['data' => $data, 'sms' => $sms, 'voice' => 0]);
                // 刷新在线状态
                $json = $api->gprsrealsingle($card->msisdn);
                $ip = $json['IP'];
                $onOff = $api->onandoffrealsingle($card->msisdn);
                $card->updateAttributes(['refresh_time' => time(), 'on_off' => $onOff, 'ip' => $ip]);
            }
        }
    }

    /**
     * 定时任务清理当月用量
     */
    public static function taskClearUsage()
    {
        Card::updateAll(['data' => 0, 'sms' => 0, 'voice' => 0]);
    }
        /**
     * 定时任务刷新卡信息
     * @param array $apiIdList Api编号列表
     * @param array $ispIdList Isp编号列表
     * @param array $uidList 用户编号列表
     * @param array $packageIdList 套餐编号列表
     * @param array $iccidList ICCID列表
     * @param array $statusList 状态列表
     */
    public static function taskRefresh($apiIdList = [], $ispIdList = [], $uidList = [], $packageIdList = [], $iccidList = [], $statusList = [])
    {
        $query = Card::find();
        if (!empty($apiIdList)) {
            $query->andWhere(['api_id' => $apiIdList]);
        }
        if (!empty($ispIdList)) {
            $query->andWhere(['isp_id' => $ispIdList]);
        }
        if (!empty($uidList)) {
            $query->andWhere(['uid' => $uidList]);
        } else {
            $query->andWhere('uid > 0 OR agent_id > 0');
        }
        if (!empty($packageIdList)) {
            $query->andWhere(['package_id' => $packageIdList]);
        }
        if (!empty($iccidList)) {
            $query->andWhere(['iccid' => $iccidList]);
        }
        if (!empty($statusList)) {
            $query->andWhere(['status' => $statusList]);
        }
        $mq = (new ActiveMqApi('/queue/card'));
        $pagination = new Pagination(['totalCount' => $query->count(), 'pageSize' => 50]);
        for ($i = 0; $i < $pagination->pageCount; $i++) {
            $pagination->setPage($i);
            $query->offset($pagination->offset)->limit($pagination->limit);
            $ispCardList = [];
            /** @var Card $card */
            foreach ($query->each() as $card) {
                if (!isset($ispCardList[$card->isp_id])) {
                    $ispCardList[$card->isp_id] = [];
                }
                $ispCardList[$card->isp_id][] = $card->iccid;
            }
            foreach ($ispCardList as $ispId => $iccidList) {
                $mq->send([
                    'action' => 'card/refresh-batch',
                    'isp_id' => $ispId,
                    'iccid_list' => $iccidList,
                ]);
            }
        }
        // 中移接口批量查询激活时间
        /** @var Isp $isp */
        foreach (Isp::find()->andWhere(['api_id' => 3])->each() as $isp) {
            try {
                $api = new \app\models\cmiot\Api($isp->data);
                $zipData = $api->downloadActiveTime(date('Ymd', time() - 86400));
                $tmpFile = Yii::getAlias('@runtime/' . date('Ymd', time() - 86400) . '.activeTime.zip');
                file_put_contents($tmpFile, $zipData);
                $zip = new ZipArchive();
                $zip->open($tmpFile);
                $content = $zip->getFromIndex(0);
                $zip->close();
                unlink($tmpFile);
                foreach (explode("\n", $content) as $line) {
                    if (empty($line)) {
                        continue;
                    }
                    list($msisdn, $activeTime) = explode(',', $line);
                    if (empty($activeTime) || $activeTime == 'null') {
                        continue;
                    }
                    $card = Card::findOne(['msisdn' => $msisdn]);
                    if (empty($card)) {
                        continue;
                    }
                    $card->updateAttributes(['active_time' => strtotime($activeTime)]);
                    $card->calcTermEnd();
                }
            } catch (\Exception $e) {
                Yii::error($e->getMessage());
                Yii::error($e->getTraceAsString());
            }
        }
    }

    /**
     * 设置卡状态
     * @param integer $status 要设置的状态
     * @return bool
     * @throws \Exception
     */
    public function setStatus($status)
    {
        if ($this->api_id == 1) { // Jasper接口
            $valueMap = [
                Card::STATUS_TEST_READY => 'TEST_READY_NAME',
                Card::STATUS_INVENTORY => 'INVENTORY_NAME',
                Card::STATUS_ACTIVATION_READY => 'ACTIVATION_READY_NAME',
                Card::STATUS_ACTIVATED => 'ACTIVATED_NAME',
                Card::STATUS_DEACTIVATED => 'DEACTIVATED_NAME',
                Card::STATUS_RETIRED => 'RETIRED_NAME',
            ];
            $api = new \app\models\jasper\Api($this->isp->data);
            $api->EditTerminal($this->iccid, 3, $valueMap[$status]);
        } elseif ($this->api_id == 2) { // 山东移动接口
            $api = new \app\models\sdiot\Api($this->isp->data);
            switch ($status) {
                case Card::STATUS_ACTIVATION_READY: // 可激活
                    if ($this->status == Card::STATUS_TEST_READY || $this->status == Card::STATUS_INVENTORY) {
                        $api->bossUnTest($this->msisdn);
                    } else {
                        $api->bossStopOpenSubs($this->msisdn, 'OpenSubs', '0', '', '', '用户手动申请开机。');
                    }
                    break;
                case Card::STATUS_DEACTIVATED: // 已停用
                    $api->bossStopOpenSubs($this->msisdn, 'StopSubs', '0', '', '', '用户手动申请停机。');
                    break;
                case Card::STATUS_TEST_READY: // 可测试
                case Card::STATUS_INVENTORY: // 库存
                case Card::STATUS_ACTIVATED: // 已激活
                    $api->bossStopOpenSubs($this->msisdn, 'OpenSubs', '0', '', '', '用户手动申请开机。');
                    break;
                case Card::STATUS_RETIRED: // 已失效
                default:
                    throw new Exception('不支持设置此状态。');
            }
        } elseif ($this->api_id == 3) { // 中移接口
            $data = json_decode($this->isp->data, true);
            $isp = Isp::findOne(['id' => $data['sdiot_isp_id']]);
            // 中移接口使用山东移动接口设置状态
            $api = new \app\models\sdiot\Api($isp->data);
            switch ($status) {
                case Card::STATUS_ACTIVATION_READY: // 可激活
                    if ($this->status == Card::STATUS_TEST_READY || $this->status == Card::STATUS_INVENTORY) {
                        $api->bossUnTest($this->msisdn);
                    } else {
                        $api->bossStopOpenSubs($this->msisdn, 'OpenSubs', '0', '', '', '用户手动申请开机。');
                    }
                    break;
                case Card::STATUS_DEACTIVATED: // 已停用
                    $api->bossStopOpenSubs($this->msisdn, 'StopSubs', '0', '', '', '用户手动申请停机。');
                    break;
                case Card::STATUS_TEST_READY: // 可测试
                case Card::STATUS_INVENTORY: // 库存
                case Card::STATUS_ACTIVATED: // 已激活
                    $api->bossStopOpenSubs($this->msisdn, 'OpenSubs', '0', '', '', '用户手动申请开机。');
                    break;
                case Card::STATUS_RETIRED: // 已失效
                default:
                    throw new Exception('不支持设置此状态。');
            }
        }
        return true;
    }

    /**
     * 刷新卡日用量
     * @param string $date 日期
     * @return bool
     */
    public function refreshDailyUsage($date)
    {
        if (empty($this->api_id)) {
            return false;
        }
        $usage = CardDailyUsage::findOne(['date' => $date, 'card_id' => $this->id]);
        if (!empty($usage)) {
            return false;
        }
        $data = 0;
        if ($this->api_id == 1) { // Jasper接口
        } elseif ($this->api_id == 2) { // 山东移动接口
            $api = new \app\models\sdiot\Api($this->isp->data);
            try {
                $json = $api->sdiotQryDayGprsUsedInfo($date, null, $this->msisdn);
                $data = $json['octetsDay'] * 1024 * 1024;
            } catch (Exception $e) {
                Yii::error($e->getMessage());
                Yii::error($e->getTraceAsString());
            }
        } elseif ($this->api_id == 3) { // 中移接口
            $data = json_decode($this->isp->data, true);
            $isp = Isp::findOne(['id' => $data['sdiot_isp_id']]);
            // 中移接口使用山东移动接口设置状态
            $api = new \app\models\sdiot\Api($isp->data);
            try {
                $json = $api->sdiotQryDayGprsUsedInfo($date, null, $this->msisdn);
                $data = $json['octetsDay'] * 1024 * 1024;
            } catch (Exception $e) {
                Yii::error($e->getMessage());
                Yii::error($e->getTraceAsString());
            }
        }
        $usage = new CardDailyUsage();
        $usage->card_id = $this->id;
        $usage->date = $date;
        $usage->data = $data;
        return $usage->save();
    }
    public function postUrl($url,$data_string){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
}
